package com.aistar.line.service.impl;

import com.aistar.common.util.IdWorker;
import com.aistar.common.util.JwtUtil;
import com.aistar.hotel.entity.Hotel;
import com.aistar.hotel.mapper.HotelMapper;
import com.aistar.line.entity.*;
import com.aistar.line.entity.Map;
import com.aistar.line.mapper.*;
import com.aistar.line.service.ILineService;
import com.aistar.line.vo.LineSpotHotel;
import com.aistar.line.vo.Reserve;
import com.aistar.line.vo.Screen;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: java类作用描述:对路线信息操作的一些业务
 * @Author: tyg
 * @CreateDate: 2019/6/23 0023
 * @Version: 1.0
 */
@Service
@Transactional
public class LineServiceImpl implements ILineService {
    @Autowired
    private LineMapper lineMapper;

    @Autowired
    private LinespotsMapper linespotsMapper;

    @Autowired
    private LinehotelsMapper linehotelsMapper;

    @Autowired
    private HotelMapper hotelMapper;

    @Autowired
    private SpotMapper spotMapper;

    @Autowired
    private LineanpaiMapper lineanpaiMapper;

    @Autowired
    private LinedissMapper linedissMapper;

    @Autowired
    private MapMapper mapMapper;

    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;


    @Override
    public PageInfo<LineSpotHotel> getPageInfo(Screen screen) {
        //分页条件
        PageHelper.startPage(screen.getPage() == null ? 1 : screen.getPage(), 10);
        //存放酒店星级筛选的路线id
        List<String> linehIds = null;

        //存放景点名筛选的路线id
        List<String> linesIds = null;

        //存放根据酒店星级和景点名筛选出来的路线id
        List<String> lineIds = null;

        //存放酒店id
        List<String> hotelIds;
        //景点id
        String spotId = "";

        //判断是否是带筛选条件查询
        //根据酒店星级筛选
        if (!"".equals(screen.getHotelStar())) {
            //查出所有这种星级的酒店id
            hotelIds = spotMapper.findByStar(screen.getHotelStar());

            linehIds = new ArrayList<>();
            for (String hotelId : hotelIds) {
                //根据酒店的id查出所关联的所有路线的id
                List<String> linehIdstemp = linehotelsMapper.findByHotelId(hotelId);
                //并集
                linehIds.addAll(linehIdstemp);
            }
            //集合去重
            linehIds = linehIds.stream().distinct().collect(Collectors.toList());
        }
        //根据景点筛选
        if (!"".equals(screen.getSpot())) {
            //查出景点的id
            spotId = spotMapper.findByName(screen.getSpot());
            //根据景点的id查出关联的所有路线的id
            linesIds = linespotsMapper.findBySpotId(spotId);
        }

        if (null != linehIds && null != linesIds) {
            //同时根据景点名和酒店星级筛选,求两个条件的路线id的交集
            linehIds.retainAll(linesIds);
            lineIds = linehIds;
        } else if (null != linehIds) {
            //只根据酒店星级筛选
            lineIds = linehIds;
        } else if (null != linesIds) {
            //只根据景点名筛选
            lineIds = linesIds;
        }


        //处理价格筛选条件
        int pirceMin = 0;
        int pirceMax = 0;
        if (!"".equals(screen.getPrice())) {
            String[] prices = screen.getPrice().split("-");
            if (prices.length == 1) {
                try {
                    pirceMin = Integer.valueOf(prices[0]);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    pirceMin = Integer.valueOf(prices[0]);
                    pirceMax = Integer.valueOf(prices[1]);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        //根据筛选条件查询路线信息
        List<Line> list = lineMapper.screen(screen.getCity(), screen.getDays(), pirceMin, pirceMax, lineIds);

        //定义一个集合用于封装LinespotHotel
        List<LineSpotHotel> lists = new ArrayList<>();

        //查询路线的酒店信息
        for (Line l : list) {
            LineSpotHotel li = new LineSpotHotel();

            //查询每个路线关联的酒店id
            List<Linehotels> linehotelsList = linehotelsMapper.findByLineId(l.getLineId());
            List<Hotel> hotels = new ArrayList<>();
            for (Linehotels linehotels : linehotelsList) {
                //根据酒店id查询酒店信息
                Hotel hotel = hotelMapper.findById(linehotels.getHotelId());
                //将查询出酒店信息放入集合
                hotels.add(hotel);
            }

            //查询每个路线关联的景点id
            List<Linespots> linespots = linespotsMapper.findByLineId(l.getLineId());
            List<Spot> spots = new ArrayList<>();
            for (Linespots linespot : linespots) {
                //根据景点id查询景点信息
                Spot spot = spotMapper.findById(linespot.getSpotId());
                //将查询出的景点信息放入集合
                spots.add(spot);
            }


            //封装酒店集合
            li.setHotels(hotels);
            //封装景点集合
            li.setSpots(spots);
            //封装路线
            li.setLine(l);

            //封装集合
            lists.add(li);
        }

        //分页查询LinespotHotel
        PageInfo<LineSpotHotel> pageInfo = new PageInfo<>(lists);

        return pageInfo;
    }

    @Override
    public void save(Line line) {
        lineMapper.save(line);
    }

    @Override
    public void delById(Line line) {
        lineMapper.delById(line.getLineId());
    }

    @Override
    public void update(Line line) {
        Line line1 = lineMapper.findById(line.getLineId());

        if (null == line) {
            return;
        }
        if (null == line.getLineName()) {
            line.setLineName(line1.getLineName());
        }
        if (null == line.getLineNo()) {
            line.setLineNo(line1.getLineNo());
        }
        if (null == line.getLineDays()) {
            line.setLineDays(line1.getLineDays());
        }
        if (null == line.getLineEnd()) {
            line.setLineEnd(line1.getLineEnd());
        }
        if (null == line.getLineShuoming()) {
            line.setLineShuoming(line1.getLineShuoming());
        }
        if (null == line.getPrice()) {
            line.setPrice(line1.getPrice());
        }
        if (null == line.getLinetypeId()) {
            line.setLinetypeId(line1.getLinetypeId());
        }
        if (null == line.getIslike()) {
            line.setIslike(line1.getIslike());
        }
        if (null == line.getStar()) {
            line.setStar(line1.getStar());
        }
        if (null == line.getTuijian()) {
            line.setTuijian(line1.getTuijian());
        }
        if (null == line.getSuccess()) {
            line.setSuccess(line1.getSuccess());
        }
        if (null == line.getOther1()) {
            line.setOther1(line1.getOther1());
        }
        if (null == line.getOther2()) {
            line.setOther2(line1.getOther2());
        }
        if (null == line.getOther3()) {
            line.setOther3(line1.getOther3());
        }

        lineMapper.update(line, line.getLineId());

    }

    @Override
    public void updatespot(List<Linespots> spots) {
        for (Linespots s : spots) {
            linespotsMapper.update(s, s.getLinespotsId());
        }
    }

    @Override
    public LineSpotHotel findById(Line line) {
        LineSpotHotel li = new LineSpotHotel();

        //查询出路线信息
        Line line1 = lineMapper.findById(line.getLineId());

        //查询出该路线所有的景点信息
        List<Linespots> linespots = linespotsMapper.findByLineId(line.getLineId());
        List<Spot> spots = new ArrayList<>();
        List<Map> maps = new ArrayList<>();
        for (Linespots linespot : linespots) {
            Spot spot = spotMapper.findById(linespot.getSpotId());
            //根据景点查询出景点的地图信息
            Map map = mapMapper.findBySpotId(spot.getSpotId());
            maps.add(map);
            spots.add(spot);
        }

        //查询出该路线所有的酒店信息
        List<Linehotels> linehotelsList = linehotelsMapper.findByLineId(line.getLineId());
        List<Hotel> hotels = new ArrayList<>();
        for (Linehotels linehotels : linehotelsList) {
            Hotel hotel = hotelMapper.findById(linehotels.getHotelId());
            hotels.add(hotel);
        }

        //查询出该路线所有的安排信息
        List<Lineanpai> lineanpais = lineanpaiMapper.findByLineId(line.getLineId());

        //查询路线所以的评论
        List<Linediss> linedisses = linedissMapper.findByLineId(line.getLineId());

        li.setLine(line1);
        li.setSpots(spots);
        li.setHotels(hotels);
        li.setLineanpais(lineanpais);
        li.setLinedisses(linedisses);
        li.setMaps(maps);

        return li;
    }

    @Override
    public List<LineSpotHotel> rankingBySuccess(Line line) {
        List<LineSpotHotel> lineSpotHotels = new ArrayList<>();
        List<String> lineids = lineMapper.ranking(line.getLineEnd());
        for (String lineid : lineids) {
            LineSpotHotel li = new LineSpotHotel();

            //查询出路线信息
            Line line1 = lineMapper.findById(lineid);

            //查询出该路线所有的景点信息
            List<Linespots> linespots = linespotsMapper.findByLineId(lineid);
            List<Spot> spots = new ArrayList<>();
            List<Map> maps = new ArrayList<>();
            for (Linespots linespot : linespots) {
                Spot spot = spotMapper.findById(linespot.getSpotId());
                //根据景点查询出景点的地图信息
                Map map = mapMapper.findBySpotId(spot.getSpotId());
                spots.add(spot);
                maps.add(map);
            }

            //查询出该路线所有的酒店信息
            List<Linehotels> linehotelsList = linehotelsMapper.findByLineId(lineid);
            List<Hotel> hotels = new ArrayList<>();
            for (Linehotels linehotels : linehotelsList) {
                Hotel hotel = hotelMapper.findById(linehotels.getHotelId());
                hotels.add(hotel);
            }

            //查询出该路线所有的安排信息
            List<Lineanpai> lineanpais = lineanpaiMapper.findByLineId(lineid);

            //查询路线所以的评论
            List<Linediss> linedisses = linedissMapper.findByLineId(line.getLineId());

            li.setLine(line1);
            li.setSpots(spots);
            li.setHotels(hotels);
            li.setLineanpais(lineanpais);
            lineSpotHotels.add(li);
            li.setLinedisses(linedisses);
            li.setMaps(maps);
        }
        return lineSpotHotels;
    }

    @Override
    public boolean collect(Collect collect) {
        //获取当前登录用户的id
//        Claims claims = (Claims) request.getAttribute("claims");
//        if (claims == null) {
//            return false;
//        }
        //        String uid = claims.getId();
        String uid = "1";

        //优先从redis中获取判断该路线当前用户是否在收藏产品
        String flag = (String) redisTemplate.opsForValue().get(uid + "_" + collect.getLineId());

        if (flag != null) {
            //存在返回true
            return true;
        } else {
            //redis不存在就去数据库查
            List<String> uids = collectMapper.findById(collect.getLineId());

            //判断路线收藏用户中是否存在当前登录用户
            if (null == uids || uids.size() == 0) {
                return false;
            } else {
                if (uids.contains(uid)) {
                    //数据库里存在返回true
                    return true;
                } else {
                    //没有返回false
                    return false;
                }
            }
        }
    }

    @Override
    public boolean addCollect(Collect collect) {
        //获取当前登录用户的id
//        Claims claims = (Claims) request.getAttribute("claims");
//        if (claims == null) {
//            return false;
//        }
//        String uid = claims.getId();
        String uid = "1";
        //添加到收藏到数据库
        try {
            collectMapper.addCollect(idWorker.nextId(), collect.getLineId(), uid);
            //添加到redis

            redisTemplate.opsForValue().set(uid + "_" + collect.getLineId(), "true");
            //路线收藏数+1
            lineMapper.updateIslike(collect.getLineId(), 1);
        } catch (Exception e) {
            return false;
//            e.printStackTrace();
        }


        return true;
    }

    @Override
    public boolean delCollect(Collect collect) {
        //获取当前登录用户的id
//        Claims claims = (Claims) request.getAttribute("claims");
//        if (claims == null) {
//            return false;
//        }
        //        String uid = claims.getId();
        String uid = "1";

        try {
            //删除收藏到数据库
            System.out.println(collect.getLineId());
            System.out.println(collectMapper.delByLineIdAndUserId(collect.getLineId(), uid));
            //删除redis里的收藏
            redisTemplate.delete(uid + "_" + collect.getLineId());
            //路线收藏数-1
            lineMapper.updateIslike(collect.getLineId(), -1);
        } catch (Exception e) {
            return false;
//            e.printStackTrace();
        }

        return true;
    }

    @Override
    public boolean addReserve(Reserve reserve) {
        //获取当前登录用户的id
//        Claims claims = (Claims) request.getAttribute("claims");
//        if (claims == null) {
//            return false;
//        }
//        String uid = claims.getId();
        String uid = "1";
        if (null != reserve && null != reserve.getLineId() && null != reserve.getDate() && null != reserve.getPeoples() ) {
            //添加到redis
            redisTemplate.opsForValue().set(uid+"_reserve_"+reserve.getLineId(),reserve);

            return true;
        }

        return false;
    }

    @Override
    public boolean delReserve(Reserve reserve) {
        //获取当前登录用户的id
        Claims claims = (Claims) request.getAttribute("claims");
        if (claims == null) {
            return false;
        }
        String uid = claims.getId();

        redisTemplate.delete(uid+"_reserve_"+reserve.getLineId());

        return true;
    }
}
